#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time
import ctypes
from config import config
from logger import logger
from utils import generate_node_id, generate_encryption_key
from node_discovery import NodeDiscovery
from network import NetworkManager
from vpn_tunnel import VPNTunnel

class P2PVPN:
    def __init__(self):
        # 初始化配置
        config.load()
        if not config.get('node_id'):
            config.set('node_id', generate_node_id())
            config.set('encryption_key', generate_encryption_key().decode())
            config.save()

        # 初始化各个模块
        self.node_discovery = NodeDiscovery()
        self.network_manager = NetworkManager()
        self.vpn_tunnel = None

    def start(self) -> None:
        """启动P2P VPN服务"""
        try:
            # 启动节点发现服务
            self.node_discovery.start()
            
            # 启动网络管理器
            self.network_manager.set_encryption_key(config.get('encryption_key').encode())
            self.network_manager.start()
            
            # 等待发现远程节点
            logger.info('等待发现远程节点...')
            while not self.node_discovery.get_remote_address():
                time.sleep(1)
            
            # 设置远程节点地址
            remote_addr = self.node_discovery.get_remote_address()
            self.network_manager.set_remote_address(remote_addr)
            logger.info(f'发现远程节点: {remote_addr}')
            
            # 启动VPN隧道
            self.vpn_tunnel = VPNTunnel(self.network_manager)
            self.vpn_tunnel.start()
            
            # 保持程序运行
            while True:
                time.sleep(1)
                
        except KeyboardInterrupt:
            logger.info('接收到停止信号')
            self.stop()
        except Exception as e:
            logger.error(f'启动P2P VPN服务失败: {e}')
            self.stop()

    def stop(self) -> None:
        """停止P2P VPN服务"""
        if self.vpn_tunnel:
            self.vpn_tunnel.stop()
        self.network_manager.stop()
        self.node_discovery.stop()
        logger.info('P2P VPN服务已停止')

def main():
    # 检查是否以管理员权限运行
    if not ctypes.windll.shell32.IsUserAnAdmin():
        print('错误: 需要管理员权限运行此程序')
        sys.exit(1)

    vpn = P2PVPN()
    vpn.start()

if __name__ == '__main__':
    main()